package com.yunhe.device.repository.device.impl;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.yunhe.common.model.ResultObject;
import com.yunhe.common.model.authority.RealStation;
import com.yunhe.common.util.StringUtil;
import com.yunhe.device.client.AuthorityClient;
import com.yunhe.device.domain.device.Device;
import com.yunhe.device.model.device.*;
import com.yunhe.device.repository.device.EquipmentRepository;
import org.neo4j.ogm.model.Result;
import org.neo4j.ogm.session.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Repository;
import com.yunhe.common.util.CollectionUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @ClassName EquipmentDao
 * @Description TODO
 * @Author HeTao
 * @Date 2021/7/16 17:11
 * @Version 1.0
 **/
@Repository
public class  EquipmentDao {

    @Autowired
    private Session session;

    @Autowired
    private AuthorityClient authorityClient;

    @Autowired
    private EquipmentRepository equipmentRepository;



    public Page<EquipmentVo> getEquipByQueryCondition(EquipmentQueryCondition equipmentQueryCondition) {

        StringBuffer cql=new StringBuffer();
        //拼接基本语句
        cql.append("match(et:DeviceType)<-[:HAS_EQUIPTYPE]-(e:Device)where 1=1 ");
        //关键字查询
        List<String> names = new ArrayList<>();
        List<String> values = new ArrayList<>();
        if(!StringUtil.isEmpty(equipmentQueryCondition.getKeywords())
                || !StringUtil.isEmpty(equipmentQueryCondition.getEquipLocation())
                || !CollectionUtil.isEmpty(equipmentQueryCondition.getRealStationIds())){

            if(!StringUtil.isEmpty(equipmentQueryCondition.getEquipLocation())){
                cql.append(" and e.equipLocation='"+equipmentQueryCondition.getEquipLocation()+"'");
            }
            if(!CollectionUtil.isEmpty(equipmentQueryCondition.getRealStationIds())){
                cql.append(" and e.ownedPark in"+equipmentQueryCondition.getRealStationIds());
            }
            if(!StringUtil.isEmpty(equipmentQueryCondition.getKeywords()) ){
                cql.append(" and (e.equipName=~'.*"+equipmentQueryCondition.getKeywords()+".*'");
                cql.append(" or e.equipSN=~'.*"+equipmentQueryCondition.getKeywords()+".*')");
            }
        }
        if(!StringUtil.isEmpty(equipmentQueryCondition.getStatus())){
            cql.append(" AND e.status='"+equipmentQueryCondition.getStatus()+"'");
        }
        if(equipmentQueryCondition.getEquipTypeId() != null){
            cql.append(" AND ID(et)="+equipmentQueryCondition.getEquipTypeId());
        }
        int skip=(equipmentQueryCondition.getPage()-1)*equipmentQueryCondition.getSize();
        String queryEnd =" RETURN DISTINCT ID(e) as id, e.status as status,ID(et) as equipTypeId,et.title as equipTypeTitle,et.name as equipTypeName," +
                "e.createTime as createTime,e.equipLocation as equipLocation," +
                "e.ownedPark as ownedPark,e.equipName as equipName,e.equipSN as equipSN  " +
                "  order by e.createTime desc  SKIP "+skip+" LIMIT "+equipmentQueryCondition.getSize();
        String countEnd =" RETURN  count(DISTINCT ID(e))";
        //分页数据查询结果
        Result result = session.query(cql.toString()+queryEnd, Maps.newHashMap());
        //查询总数
        Integer total  =session.queryForObject(Integer.class,cql.toString()+countEnd, Maps.newHashMap());
        //封装为分页类
        List<EquipmentVo> equipmentVos = new ArrayList<>();
        if(result != null){
            for (Map<String, Object> map : result) {
                EquipmentVo equipmentVo = JSONObject.parseObject(JSONObject.toJSONString(map), EquipmentVo.class);
                equipmentVos.add(equipmentVo);
            }
        }
        Page<EquipmentVo> page = null;
        if(!CollectionUtil.isEmpty(equipmentVos)){
            List<EquipmentVo> content= Lists.newArrayList(equipmentVos);
            for (EquipmentVo equipmentVo : content) {
                if(equipmentVo.getOwnedPark() != null){
                    ResponseEntity<ResultObject<RealStation>> responseEntity = authorityClient.findByRealStationId(equipmentVo.getOwnedPark());
                    if(responseEntity != null &&responseEntity.getStatusCode().is2xxSuccessful()){
                        RealStation realStation = (RealStation) responseEntity.getBody().getResults();
                        if(realStation != null){
                            equipmentVo.setOwnedParkName(StringUtil.isEmpty(realStation.getAbbreviationName())?realStation.getEnterpriseFullName():realStation.getAbbreviationName());
                        }
                    }
                }
                //查询归属厂房
                String officeName = equipmentRepository.findOfficeNameByEquipId(equipmentVo.getId());
                equipmentVo.setOwnedOfficeName(officeName);
            }
            Pageable pageable= PageRequest.of(equipmentQueryCondition.getPage()-1,equipmentQueryCondition.getSize());
            page=new PageImpl(content,pageable,total);
        }
        return page;
    }

    public Map<String, String> getNameMap(List<EquipAttrValue> equipAttrValues) {
        return equipAttrValues.stream().collect(Collectors.toMap(EquipAttrValue::getName, EquipAttrValue::getValue));
    }

    private Map<String, String> findEquipAttrValueByEquipIdAndEquipTypeId(Long id, Long equipTypeId) {
        List<EquipAttrValue> equipAttrValues = new ArrayList<>();
        StringBuffer cql=new StringBuffer();
        //拼接基本语句
        cql.append("match (e:Device)-[heta:HAS_EQUIPTYPEATTR]->(ea:EquipmentAttributes) where 1=1");
        cql.append(" AND ID(e)="+id);
        cql.append(" AND heta.equipTypeId="+equipTypeId);
        String queryEnd =" RETURN heta.value as value ,ea.name as name";
        Result result = session.query(cql.toString()+queryEnd, Maps.newHashMap());
        if(result != null){
            for (Map<String, Object> map : result) {
                EquipAttrValue equipAttrValue = JSONObject.parseObject(JSONObject.toJSONString(map), EquipAttrValue.class);
                equipAttrValues.add(equipAttrValue);
            }
        }
        if(!CollectionUtil.isEmpty(equipAttrValues)){
            return getNameMap(equipAttrValues);
        }
        return null;
    }

    public List<EquipAttrValueVo> getEquipAttrValue(Long id, Long equipTypeId) {
        List<EquipAttrValueVo> equipAttrValueVos = new ArrayList<>();
        StringBuffer cql=new StringBuffer();
        //拼接基本语句
        cql.append("match (e:Device)-[heta:HAS_EQUIPTYPEATTR]->(ea:EquipmentAttributes) where 1=1");
        cql.append(" AND ID(e)="+id);
        cql.append(" AND heta.equipTypeId="+equipTypeId);
        String queryEnd =" RETURN heta.value as value,ea.name as name,ea.title as title, ID(ea) as id,ea.url as url,'01' as type,ea.componentType as componentType ";
        Result result = session.query(cql.toString() + queryEnd, Maps.newHashMap());
        if(result != null){
            for (Map<String, Object> map : result) {
                EquipAttrValueVo equipAttrValueVo = JSONObject.parseObject(JSONObject.toJSONString(map), EquipAttrValueVo.class);
                equipAttrValueVos.add(equipAttrValueVo);
            }
        }
        return equipAttrValueVos;
    }

    public List<EquipAnlogTypeVo> getEquipAndAnlogTypeById(EquipAnlogTypeQueryCondition equipAnlogTypeQueryCondition) {
        StringBuffer cql=new StringBuffer();
        //拼接基本语句
        cql.append("match(e:Device)-[heta:HAS_EQUIPTYPEANLOGTYPE]->(at:PointDataType) where 1=1 ");
        if(equipAnlogTypeQueryCondition.getEquipId() != null){
            cql.append(" AND ID(e)="+equipAnlogTypeQueryCondition.getEquipId());
        }
        if(equipAnlogTypeQueryCondition.getEquipTypeId() != null){
            cql.append(" AND heta.equipTypeId="+equipAnlogTypeQueryCondition.getEquipTypeId());
        }
//        if(!StringUtil.isEmpty(equipAnlogTypeQueryCondition.getAnlogTypeTitle())){
//            cql.append(" AND u.title=~'.*"+equipAnlogTypeQueryCondition.getAnlogTypeTitle()+".*'");
//        }
        String queryEnd =" RETURN DISTINCT ID(at) as id, at.title as title ,at.name as name,at.type as type ,heta.value as value,at.backType as backType,ID(heta) as relationshipId,at.createTime as createTime  "+
                "  order by at.createTime desc";
        //分页数据查询结果
        Result result = session.query(cql.toString()+queryEnd, Maps.newHashMap());
        //封装为分页类
        List<EquipAnlogTypeVo> equipAnlogTypeVos = new ArrayList<>();
        if(result != null){
            for (Map<String, Object> map : result) {
                EquipAnlogTypeVo equipAnlogTypeVo = JSONObject.parseObject(JSONObject.toJSONString(map), EquipAnlogTypeVo.class);
                equipAnlogTypeVos.add(equipAnlogTypeVo);
            }
        }
        return equipAnlogTypeVos;
    }

    public List<Device> getEquipByOwnePark(List<Long> realStations) {
        StringBuffer cql=new StringBuffer();
        //拼接基本语句
        cql.append("match(et:DeviceType)<-[:HAS_EQUIPTYPE]-(e:Device) where 1=1 ");
        if(!CollectionUtil.isEmpty(realStations)){
            cql.append(" and e.ownedPark IN "+realStations);
        }
        String queryEnd =" RETURN DISTINCT ID(e) as id, e.status as status,et.name as equipTypeName,et.title as equipTypeTitle, e.createTime as createTime" +
                "  order by e.createTime desc";
        Result result = session.query(cql.toString()+queryEnd, Maps.newHashMap());
        //封装为分页类
        List<Device> equipments = new ArrayList<>();
        if(result != null){
            for (Map<String, Object> map : result) {
                Device equipment = JSONObject.parseObject(JSONObject.toJSONString(map), Device.class);
                equipments.add(equipment);
            }
        }
        return equipments;
    }

    public List<EquipAttrValueVo> getCustomEquipAttrValue(Long id) {
        List<EquipAttrValueVo> equipAttrValueVos = new ArrayList<>();
        StringBuffer cql=new StringBuffer();
        //拼接基本语句
        cql.append("match (e:Device)-[heta:HAS_CUSTOMEQUIPTYPEATTR]->(ea:EquipmentAttributes) where 1=1");
        cql.append(" AND ID(e)="+id);
        String queryEnd =" RETURN heta.value as value,ea.name as name,ea.title as title, ID(ea) as id,ea.url as url,ea.type as type,ea.componentType as componentType ";
        Result result = session.query(cql.toString() + queryEnd, Maps.newHashMap());
        if(result != null){
            for (Map<String, Object> map : result) {
                EquipAttrValueVo equipAttrValueVo = JSONObject.parseObject(JSONObject.toJSONString(map), EquipAttrValueVo.class);
                equipAttrValueVos.add(equipAttrValueVo);
            }
        }
        return equipAttrValueVos;
    }
}
